#ifndef NET_CONNECTOR_H
#define NET_CONNECTOR_H

#include <memory>
#include <atomic>
#include "InetAddress.h"

class EventLoop;
class Channel;

class Connector : public std::enable_shared_from_this<Connector>
{
public:
	typedef std::function<void(int sockfd)> NewConnectionCallback;
	Connector(EventLoop* loop, const InetAddress& addr);
	~Connector();

	void start();			//can be called in any thread
	void restart();			//must be called in loop thread
	void stop();			// can be called in any thread

	void setNewConnectionCallback(NewConnectionCallback cb)
	{
		newConnectionCallback_ = cb;
	}

	const InetAddress& serverAddress(){ return m_serverAddr; }
private:
	enum States { kDisconnected,kConnecting,kConnected};
	static const int kMaxRetryDelayMs = 30 * 1000;		//30s重试
	static const int kInitRetryDelayMs = 500;

	void setState(States s){ m_state = s; }
	void startInLoop();
	void stopInLoop();
	void connect();
	void connecting(int sockfd);
	void handleWrite();
	void handleError();
	int removeAndResetChannel();
	void resetChannel();
	void retry(int sockfd);

	EventLoop* m_pLoop;
	InetAddress m_serverAddr;
	States m_state;
	//Channel仅仅用来当连接建立完毕时通知socket变得可写，然后马上将其reset
	std::shared_ptr<Channel> m_pChannel;
	std::atomic<bool> m_bConnect;
	int m_retryDelayMs;
	NewConnectionCallback newConnectionCallback_;
};


#endif  // NET_CONNECTOR_H
